package com.ruoyi.framework.security.filter.ykz;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 过滤/login/ykz 请求 获取 auth_code
 */
@Slf4j
public class YKZAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	
	public YKZAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/ykz", HttpMethod.GET.name()));
    }

	@Override
    public Authentication attemptAuthentication(
            HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals(HttpMethod.GET.name())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //授权码.
        String code = request.getParameter("auth_code");
        log.info("渝快政登录请求auth_code：{}", code);
        String corpId = "govding";
        if (StringUtils.isEmpty(code)) {
            throw new RuntimeException("ykz authentication code can not be empty!");
        }
        logger.info("YKZcorpId为："+corpId + ",code:" + code);
        System.out.println("YKZcorpId为："+corpId + ",code:" + code);
        YKZAuthenticationToken authToken = new YKZAuthenticationToken(code);
        // Allow subclasses to set the "details" property
        setDetails(request, authToken);

        return this.getAuthenticationManager().authenticate(authToken);
    }

    /**
     * Provided so that subclasses may configure what is put into the authentication
     * request's details property.
     *
     * @param request     that an authentication request is being created for
     * @param authRequest the authentication request object that should have its details
     *                    set
     */
    private void setDetails(HttpServletRequest request, YKZAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

	
	

}
